package com.browsesoft.htmlcomponent;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.browsesoft.Entity;

/**
 * 排序动作
 */
public class SortAction {
	public SortAction() {
	}

	/**
	 * 得到排序结果
	 * 
	 * @param object
	 *            要排序的对象集合
	 * @param columnName
	 *            那一列排序
	 */
	public void sort(Object object, String columnName, boolean isAsc) {
		// 如果object是链表
		if (object instanceof List) {
			Collections
					.sort((List) object, new MyComparator(columnName, isAsc));
		}
		// 如果object是String[][]
		else if (object instanceof String[][]) {
			Arrays.sort((String[]) object, new MyComparator(columnName, isAsc));
		}
	}

	class MyComparator implements Comparator {
		String name = null;

		boolean isAsc = false;

		public MyComparator(String name, boolean isAsc) {
			this.name = name;
			this.isAsc = isAsc;
		}

		public int compare(Object a, Object b) {
			if (a instanceof Entity) {
				Entity aa = (Entity) a;
				String aaa = (String) aa.getAttributes().get(this.name);
				Entity bb = (Entity) b;
				String bbb = (String) bb.getAttributes().get(this.name);
				if (isAsc) {
					return aaa.compareTo(bbb);
				} else {
					return bbb.compareTo(aaa);
				}
			} else if (a instanceof String) {
				if (isAsc) {
					return ((String) a).compareTo((String) b);
				} else {
					return ((String) b).compareTo((String) a);
				}
			} else {
				if (isAsc) {
					return a.hashCode() - b.hashCode();
				} else {
					return b.hashCode() - a.hashCode();
				}

			}
		}
	}

}